<template>
  <div class="failure-handling-container">
    <a-breadcrumb class="breadcrumb">
      <a-breadcrumb-item>
        <router-link to="/salvation">超度与救赎</router-link>
      </a-breadcrumb-item>
      <a-breadcrumb-item>
        <router-link to="/salvation/redemption-plan">救赎计划管理</router-link>
      </a-breadcrumb-item>
      <a-breadcrumb-item>失败处理</a-breadcrumb-item>
    </a-breadcrumb>

    <div class="page-header">
      <h1 class="page-title">救赎失败处理</h1>
      <p class="page-subtitle">处理任务失败案例，制定重新救赎方案</p>
      <a-button type="primary" @click="handleCreate">
        <template #icon><PlusOutlined /></template>
        新建处理方案
      </a-button>
    </div>

    <!-- 统计卡片 -->
    <div class="stats-cards">
      <a-card class="stat-card">
        <div class="stat-content">
          <ExclamationCircleOutlined class="stat-icon" />
          <div class="stat-info">
            <div class="stat-value">23</div>
            <div class="stat-label">待处理失败</div>
          </div>
        </div>
      </a-card>

      <a-card class="stat-card">
        <div class="stat-content">
          <ReloadOutlined class="stat-icon" />
          <div class="stat-info">
            <div class="stat-value">156</div>
            <div class="stat-label">重新安排</div>
          </div>
        </div>
      </a-card>

      <a-card class="stat-card">
        <div class="stat-content">
          <CheckCircleOutlined class="stat-icon" />
          <div class="stat-info">
            <div class="stat-value">89</div>
            <div class="stat-label">处理完成</div>
          </div>
        </div>
      </a-card>

      <a-card class="stat-card">
        <div class="stat-content">
          <BarChartOutlined class="stat-icon" />
          <div class="stat-info">
            <div class="stat-value">72.5%</div>
            <div class="stat-label">重新成功率</div>
          </div>
        </div>
      </a-card>
    </div>

    <!-- 失败案例 -->
    <a-card class="table-card">
      <a-table :columns="columns" :data-source="failureData" :pagination="pagination" row-key="id">
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'participant'">
            <div class="participant-info">
              <a-avatar :src="record.avatar" :size="32">{{ record.participantName.charAt(0) }}</a-avatar>
              <div>
                <div class="name">{{ record.participantName }}</div>
                <div class="id">ID: {{ record.participantId }}</div>
              </div>
            </div>
          </template>

          <template v-else-if="column.key === 'task'">
            <div class="task-info">
              <div class="task-name">{{ record.taskName }}</div>
              <a-tag :color="getDifficultyColor(record.difficulty)" size="small">
                {{ getDifficultyText(record.difficulty) }}
              </a-tag>
            </div>
          </template>

          <template v-else-if="column.key === 'reason'">
            <a-tag :color="getReasonColor(record.failureReason)">
              {{ getReasonText(record.failureReason) }}
            </a-tag>
          </template>

          <template v-else-if="column.key === 'penalty'">
            <div class="penalty-info">
              <div class="penalty-value">-{{ record.penaltyAmount }}功德</div>
              <div class="penalty-status">{{ record.penaltyApplied ? '已执行' : '待执行' }}</div>
            </div>
          </template>

          <template v-else-if="column.key === 'status'">
            <a-tag :color="getStatusColor(record.handlingStatus)">
              {{ getStatusText(record.handlingStatus) }}
            </a-tag>
          </template>

          <template v-else-if="column.key === 'actions'">
            <a-dropdown>
              <template #overlay>
                <a-menu @click="handleMenuClick($event, record)">
                  <a-menu-item key="view">查看详情</a-menu-item>
                  <a-menu-item key="reassign">重新分配</a-menu-item>
                  <a-menu-item key="modify">修改惩罚</a-menu-item>
                  <a-menu-item key="appeal">申诉处理</a-menu-item>
                </a-menu>
              </template>
              <a-button type="text">操作 <DownOutlined /></a-button>
            </a-dropdown>
          </template>
        </template>
      </a-table>
    </a-card>

    <!-- 处理方案模态框 -->
    <a-modal v-model:open="showHandlingModal" title="制定处理方案" width="800px" @ok="saveHandling" :confirmLoading="saving">
      <a-form layout="vertical" v-if="selectedCase">
        <a-form-item label="失败案例">
          <a-input :value="`${selectedCase.name} - ${selectedCase.taskName}`" disabled />
        </a-form-item>

        <a-form-item label="失败原因">
          <a-input :value="getReasonText(selectedCase.failureReason)" disabled />
        </a-form-item>

        <a-form-item label="处理计划" required>
          <a-textarea v-model:value="handlingForm.handlingPlan" :rows="4" placeholder="请描述详细的处理计划和步骤" />
        </a-form-item>

        <a-form-item label="具体措施" required>
          <a-textarea v-model:value="handlingForm.actionTaken" :rows="3" placeholder="请描述将要采取的具体措施" />
        </a-form-item>

        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="惩罚分数">
              <a-input-number v-model:value="handlingForm.penaltyPoints" :min="0" :max="500" style="width: 100%" placeholder="扣除功德分数" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="处理期限">
              <a-date-picker v-model:value="handlingForm.deadline" style="width: 100%" placeholder="选择处理期限" />
            </a-form-item>
          </a-col>
        </a-row>

        <a-form-item label="重新分配对象">
          <a-select v-model:value="handlingForm.reassignTo" placeholder="选择重新分配的执行人">
            <a-select-option value="">无需重新分配</a-select-option>
            <a-select-option value="volunteer1">志愿者A</a-select-option>
            <a-select-option value="volunteer2">志愿者B</a-select-option>
            <a-select-option value="volunteer3">志愿者C</a-select-option>
          </a-select>
        </a-form-item>

        <a-form-item>
          <a-checkbox v-model:checked="handlingForm.trainingRequired"> 需要参加额外培训 </a-checkbox>
        </a-form-item>

        <a-form-item label="备注说明">
          <a-textarea v-model:value="handlingForm.notes" :rows="2" placeholder="请输入处理备注和说明" />
        </a-form-item>
      </a-form>
    </a-modal>

    <!-- 新建处理方案选择案例模态框 -->
    <a-modal v-model:open="showCreateModal" title="新建处理方案" width="1000px" :footer="null">
      <div class="create-plan-content">
        <a-tabs v-model:activeKey="createMode" @change="handleCreateModeChange">
          <a-tab-pane key="select" tab="选择失败案例">
            <div class="case-selection">
              <div class="selection-header">
                <h4>选择需要制定处理方案的失败案例</h4>
                <a-space>
                  <a-input-search v-model:value="caseSearchKeyword" placeholder="搜索参与者或任务名称" style="width: 250px" @search="searchCases" />
                  <a-select v-model:value="caseStatusFilter" placeholder="筛选状态" style="width: 120px" @change="filterCases">
                    <a-select-option value="">全部状态</a-select-option>
                    <a-select-option value="pending">待处理</a-select-option>
                    <a-select-option value="processing">处理中</a-select-option>
                    <a-select-option value="appealing">申诉中</a-select-option>
                  </a-select>
                  <a-button type="primary" @click="batchCreatePlans" :disabled="selectedCases.length === 0"> 批量制定方案 ({{ selectedCases.length }}) </a-button>
                </a-space>
              </div>

              <a-table :columns="selectionColumns" :data-source="filteredCases" :pagination="{ pageSize: 5 }" row-key="id" :row-selection="{ selectedRowKeys: selectedCases, onChange: onCaseSelectionChange }" size="small">
                <template #bodyCell="{ column, record }">
                  <template v-if="column.key === 'participant'">
                    <div class="participant-info">
                      <a-avatar :src="record.avatar" :size="32">{{ record.participantName.charAt(0) }}</a-avatar>
                      <div>
                        <div class="name">{{ record.participantName }}</div>
                        <div class="id">ID: {{ record.participantId }}</div>
                      </div>
                    </div>
                  </template>

                  <template v-else-if="column.key === 'task'">
                    <div class="task-info">
                      <div class="task-name">{{ record.taskName }}</div>
                      <a-tag :color="getDifficultyColor(record.difficulty)" size="small">
                        {{ getDifficultyText(record.difficulty) }}
                      </a-tag>
                    </div>
                  </template>

                  <template v-else-if="column.key === 'reason'">
                    <a-tag :color="getReasonColor(record.failureReason)">
                      {{ getReasonText(record.failureReason) }}
                    </a-tag>
                  </template>

                  <template v-else-if="column.key === 'status'">
                    <a-tag :color="getStatusColor(record.handlingStatus)">
                      {{ getStatusText(record.handlingStatus) }}
                    </a-tag>
                  </template>

                  <template v-else-if="column.key === 'actions'">
                    <a-button type="link" size="small" @click="createSinglePlan(record)"> 制定方案 </a-button>
                  </template>
                </template>
              </a-table>
            </div>
          </a-tab-pane>

          <a-tab-pane key="quick" tab="快速处理方案">
            <div class="quick-plan">
              <a-form layout="vertical" :model="quickPlanForm" ref="quickPlanFormRef">
                <a-row :gutter="24">
                  <a-col :span="12">
                    <a-form-item label="方案模板" name="template" required>
                      <a-select v-model:value="quickPlanForm.template" placeholder="选择处理方案模板" @change="handleTemplateChange">
                        <a-select-option value="timeout">超时处理模板</a-select-option>
                        <a-select-option value="incomplete">未完成处理模板</a-select-option>
                        <a-select-option value="violation">违规处理模板</a-select-option>
                        <a-select-option value="abandon">放弃处理模板</a-select-option>
                        <a-select-option value="custom">自定义模板</a-select-option>
                      </a-select>
                    </a-form-item>
                  </a-col>
                  <a-col :span="12">
                    <a-form-item label="处理优先级" name="priority" required>
                      <a-select v-model:value="quickPlanForm.priority" placeholder="选择处理优先级">
                        <a-select-option value="urgent">紧急</a-select-option>
                        <a-select-option value="high">高</a-select-option>
                        <a-select-option value="medium">中等</a-select-option>
                        <a-select-option value="low">低</a-select-option>
                      </a-select>
                    </a-form-item>
                  </a-col>
                </a-row>

                <a-form-item label="方案标题" name="title" required>
                  <a-input v-model:value="quickPlanForm.title" placeholder="请输入处理方案标题" />
                </a-form-item>

                <a-form-item label="处理计划" name="plan" required>
                  <a-textarea v-model:value="quickPlanForm.plan" :rows="4" placeholder="请描述详细的处理计划和步骤" />
                </a-form-item>

                <a-form-item label="具体措施" name="actions" required>
                  <a-textarea v-model:value="quickPlanForm.actions" :rows="3" placeholder="请描述将要采取的具体措施" />
                </a-form-item>

                <a-row :gutter="16">
                  <a-col :span="8">
                    <a-form-item label="建议惩罚分数" name="penaltyPoints">
                      <a-input-number v-model:value="quickPlanForm.penaltyPoints" :min="0" :max="500" style="width: 100%" placeholder="建议扣除功德分数" />
                    </a-form-item>
                  </a-col>
                  <a-col :span="8">
                    <a-form-item label="处理期限" name="deadline">
                      <a-date-picker v-model:value="quickPlanForm.deadline" style="width: 100%" placeholder="选择处理期限" />
                    </a-form-item>
                  </a-col>
                  <a-col :span="8">
                    <a-form-item label="重试次数" name="retryCount">
                      <a-input-number v-model:value="quickPlanForm.retryCount" :min="0" :max="3" style="width: 100%" placeholder="允许重试次数" />
                    </a-form-item>
                  </a-col>
                </a-row>

                <a-form-item label="处理选项">
                  <a-checkbox-group v-model:value="quickPlanForm.options">
                    <a-checkbox value="training">需要额外培训</a-checkbox>
                    <a-checkbox value="reassign">需要重新分配</a-checkbox>
                    <a-checkbox value="supervision">需要加强监督</a-checkbox>
                    <a-checkbox value="counseling">需要心理辅导</a-checkbox>
                  </a-checkbox-group>
                </a-form-item>

                <a-form-item label="适用案例类型">
                  <a-checkbox-group v-model:value="quickPlanForm.applicableTypes">
                    <a-checkbox value="timeout">超时案例</a-checkbox>
                    <a-checkbox value="incomplete">未完成案例</a-checkbox>
                    <a-checkbox value="violation">违规案例</a-checkbox>
                    <a-checkbox value="abandon">放弃案例</a-checkbox>
                  </a-checkbox-group>
                </a-form-item>

                <a-form-item label="备注说明" name="notes">
                  <a-textarea v-model:value="quickPlanForm.notes" :rows="2" placeholder="请输入方案备注和说明" />
                </a-form-item>

                <a-form-item>
                  <a-space>
                    <a-button type="primary" @click="saveQuickPlan" :loading="quickPlanSaving"> 保存快速方案 </a-button>
                    <a-button @click="previewQuickPlan"> 预览方案 </a-button>
                    <a-button @click="resetQuickPlanForm"> 重置表单 </a-button>
                  </a-space>
                </a-form-item>
              </a-form>
            </div>
          </a-tab-pane>

          <a-tab-pane key="template" tab="方案模板管理">
            <div class="template-management">
              <div class="template-header">
                <h4>处理方案模板库</h4>
                <a-button type="primary" @click="showTemplateModal = true">
                  <template #icon><PlusOutlined /></template>
                  新建模板
                </a-button>
              </div>

              <div class="template-list">
                <a-row :gutter="16">
                  <a-col :span="8" v-for="template in planTemplates" :key="template.id">
                    <a-card class="template-card" size="small">
                      <template #title>
                        <div class="template-title">
                          {{ template.name }}
                          <a-tag :color="getPriorityColor(template.priority)" size="small">
                            {{ getPriorityText(template.priority) }}
                          </a-tag>
                        </div>
                      </template>
                      <template #extra>
                        <a-dropdown>
                          <a-button type="text" size="small">
                            <MoreOutlined />
                          </a-button>
                          <template #overlay>
                            <a-menu @click="handleTemplateAction($event, template)">
                              <a-menu-item key="use">使用模板</a-menu-item>
                              <a-menu-item key="edit">编辑模板</a-menu-item>
                              <a-menu-item key="copy">复制模板</a-menu-item>
                              <a-menu-item key="delete">删除模板</a-menu-item>
                            </a-menu>
                          </template>
                        </a-dropdown>
                      </template>
                      <div class="template-content">
                        <p class="template-description">{{ template.description }}</p>
                        <div class="template-stats">
                          <span class="stat-item"> <TeamOutlined /> 适用: {{ template.applicableTypes.join(', ') }} </span>
                          <span class="stat-item"> <CalendarOutlined /> 使用: {{ template.usageCount }}次 </span>
                        </div>
                      </div>
                    </a-card>
                  </a-col>
                </a-row>
              </div>
            </div>
          </a-tab-pane>
        </a-tabs>
      </div>
    </a-modal>

    <!-- 模板编辑模态框 -->
    <a-modal v-model:open="showTemplateModal" title="编辑处理方案模板" width="600px" @ok="saveTemplate" :confirmLoading="templateSaving">
      <a-form layout="vertical" :model="templateForm" ref="templateFormRef">
        <a-form-item label="模板名称" name="name" required>
          <a-input v-model:value="templateForm.name" placeholder="请输入模板名称" />
        </a-form-item>

        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="模板类型" name="type" required>
              <a-select v-model:value="templateForm.type" placeholder="选择模板类型">
                <a-select-option value="timeout">超时处理</a-select-option>
                <a-select-option value="incomplete">未完成处理</a-select-option>
                <a-select-option value="violation">违规处理</a-select-option>
                <a-select-option value="abandon">放弃处理</a-select-option>
                <a-select-option value="custom">自定义</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="优先级" name="priority" required>
              <a-select v-model:value="templateForm.priority" placeholder="选择优先级">
                <a-select-option value="urgent">紧急</a-select-option>
                <a-select-option value="high">高</a-select-option>
                <a-select-option value="medium">中等</a-select-option>
                <a-select-option value="low">低</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>

        <a-form-item label="模板描述" name="description" required>
          <a-textarea v-model:value="templateForm.description" :rows="3" placeholder="请描述模板的用途和适用场景" />
        </a-form-item>

        <a-form-item label="处理计划模板" name="planTemplate" required>
          <a-textarea v-model:value="templateForm.planTemplate" :rows="4" placeholder="请输入处理计划模板内容" />
        </a-form-item>

        <a-form-item label="措施模板" name="actionsTemplate" required>
          <a-textarea v-model:value="templateForm.actionsTemplate" :rows="3" placeholder="请输入具体措施模板内容" />
        </a-form-item>

        <a-form-item label="适用案例类型" name="applicableTypes" required>
          <a-checkbox-group v-model:value="templateForm.applicableTypes">
            <a-checkbox value="timeout">超时案例</a-checkbox>
            <a-checkbox value="incomplete">未完成案例</a-checkbox>
            <a-checkbox value="violation">违规案例</a-checkbox>
            <a-checkbox value="abandon">放弃案例</a-checkbox>
          </a-checkbox-group>
        </a-form-item>
      </a-form>
    </a-modal>

    <!-- 方案预览模态框 -->
    <a-modal v-model:open="showPreviewModal" title="方案预览" width="700px" :footer="null">
      <div class="plan-preview" v-if="previewPlan">
        <a-descriptions title="方案信息" :column="2" bordered size="small">
          <a-descriptions-item label="方案标题">{{ previewPlan.title }}</a-descriptions-item>
          <a-descriptions-item label="优先级">
            <a-tag :color="getPriorityColor(previewPlan.priority)">
              {{ getPriorityText(previewPlan.priority) }}
            </a-tag>
          </a-descriptions-item>
          <a-descriptions-item label="建议惩罚分数">{{ previewPlan.penaltyPoints }}功德</a-descriptions-item>
          <a-descriptions-item label="处理期限">{{ previewPlan.deadline }}</a-descriptions-item>
          <a-descriptions-item label="重试次数">{{ previewPlan.retryCount }}次</a-descriptions-item>
          <a-descriptions-item label="适用案例">{{ previewPlan.applicableTypes.join(', ') }}</a-descriptions-item>
        </a-descriptions>

        <a-divider>处理计划</a-divider>
        <div class="plan-content">{{ previewPlan.plan }}</div>

        <a-divider>具体措施</a-divider>
        <div class="actions-content">{{ previewPlan.actions }}</div>

        <a-divider>处理选项</a-divider>
        <div class="options-content">
          <a-tag v-for="option in previewPlan.options" :key="option" color="blue">
            {{ getOptionText(option) }}
          </a-tag>
        </div>

        <a-divider v-if="previewPlan.notes">备注说明</a-divider>
        <div class="notes-content" v-if="previewPlan.notes">{{ previewPlan.notes }}</div>
      </div>
    </a-modal>

    <!-- 详情查看模态框 -->
    <a-modal v-model:open="showDetailModal" title="失败案例详情" width="900px" :footer="null">
      <div class="failure-detail" v-if="selectedCase">
        <a-row :gutter="24">
          <a-col :span="8">
            <a-card class="participant-card">
              <div class="participant-info">
                <a-avatar :size="80" :src="selectedCase.avatar" />
                <h3>{{ selectedCase.name }}</h3>
                <a-tag :color="getLevelColor(selectedCase.level)"> LV.{{ selectedCase.level }} </a-tag>
                <div class="contact-info">
                  <p><UserSwitchOutlined /> {{ selectedCase.phoneNumber }}</p>
                  <p><FileTextOutlined /> {{ selectedCase.email }}</p>
                </div>
                <div class="merit-info">
                  <span class="merit-total"
                    >功德总值: <strong>{{ selectedCase.totalMerit }}</strong></span
                  >
                </div>
                <div class="attempts-info">
                  <a-alert :message="`失败次数: ${selectedCase.previousAttempts + 1}`" type="warning" show-icon />
                </div>
              </div>
            </a-card>
          </a-col>

          <a-col :span="16">
            <a-card class="failure-info-card">
              <h4>{{ selectedCase.taskName }}</h4>
              <p class="failure-date">失败时间: {{ selectedCase.failureDate }}</p>

              <a-divider>失败详情</a-divider>

              <a-row :gutter="16" class="failure-overview">
                <a-col :span="8">
                  <a-statistic title="失败原因" :value="getReasonText(selectedCase.failureReason)" />
                </a-col>
                <a-col :span="8">
                  <a-statistic title="惩罚分数" :value="selectedCase.penaltyPoints" suffix="分" :value-style="{ color: '#ff4d4f' }" />
                </a-col>
                <a-col :span="8">
                  <a-statistic title="处理状态" :value="getStatusText(selectedCase.status)" />
                </a-col>
              </a-row>

              <div class="failure-description">
                <a-divider>失败描述</a-divider>
                <p>{{ selectedCase.failureDescription }}</p>
              </div>

              <div class="handling-info" v-if="selectedCase.handlingPlan">
                <a-divider>处理方案</a-divider>
                <p><strong>处理计划:</strong> {{ selectedCase.handlingPlan }}</p>
                <p v-if="selectedCase.actionTaken"><strong>采取措施:</strong> {{ selectedCase.actionTaken }}</p>
                <p v-if="selectedCase.handlerName"><strong>处理人员:</strong> {{ selectedCase.handlerName }}</p>
                <p v-if="selectedCase.handlingDate"><strong>处理时间:</strong> {{ selectedCase.handlingDate }}</p>
              </div>

              <div class="appeal-info" v-if="selectedCase.appealStatus">
                <a-divider>申诉信息</a-divider>
                <a-tag :color="getAppealStatusColor(selectedCase.appealStatus)">
                  {{ getAppealStatusText(selectedCase.appealStatus) }}
                </a-tag>
                <p v-if="selectedCase.appealReason"><strong>申诉理由:</strong> {{ selectedCase.appealReason }}</p>
              </div>
            </a-card>
          </a-col>
        </a-row>

        <a-card class="additional-info" style="margin-top: 16px">
          <a-descriptions :column="3" bordered>
            <a-descriptions-item label="任务难度">
              <a-tag :color="getDifficultyColor(selectedCase.taskDifficulty)">
                {{ getDifficultyText(selectedCase.taskDifficulty) }}
              </a-tag>
            </a-descriptions-item>
            <a-descriptions-item label="任务时长">{{ selectedCase.taskDuration }} 天</a-descriptions-item>
            <a-descriptions-item label="分配人员">{{ selectedCase.assignedBy }}</a-descriptions-item>
            <a-descriptions-item label="失败次数">{{ selectedCase.previousAttempts + 1 }} 次</a-descriptions-item>
            <a-descriptions-item label="处理期限">{{ selectedCase.deadline }}</a-descriptions-item>
            <a-descriptions-item label="申诉状态">
              {{ selectedCase.appealStatus ? getAppealStatusText(selectedCase.appealStatus) : '无申诉' }}
            </a-descriptions-item>
            <a-descriptions-item label="备注说明" :span="3">{{ selectedCase.notes || '无' }}</a-descriptions-item>
          </a-descriptions>
        </a-card>
      </div>
    </a-modal>

    <!-- 重新分配模态框 -->
    <a-modal v-model:open="showReassignModal" title="重新分配任务" width="600px" @ok="submitReassign" :confirmLoading="saving">
      <a-form layout="vertical" v-if="selectedCase">
        <a-form-item label="当前失败者">
          <a-input :value="selectedCase.name" disabled />
        </a-form-item>

        <a-form-item label="任务名称">
          <a-input :value="selectedCase.taskName" disabled />
        </a-form-item>

        <a-form-item label="重新分配给" required>
          <a-select v-model:value="reassignForm.newAssignee" placeholder="选择新的执行人">
            <a-select-option value="volunteer1">志愿者A</a-select-option>
            <a-select-option value="volunteer2">志愿者B</a-select-option>
            <a-select-option value="volunteer3">志愿者C</a-select-option>
            <a-select-option value="volunteer4">志愿者D</a-select-option>
          </a-select>
        </a-form-item>

        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="新的截止时间" required>
              <a-date-picker v-model:value="reassignForm.newDeadline" style="width: 100%" placeholder="选择新期限" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="调整难度">
              <a-select v-model:value="reassignForm.adjustedDifficulty" placeholder="选择难度">
                <a-select-option :value="1">简单</a-select-option>
                <a-select-option :value="2">普通</a-select-option>
                <a-select-option :value="3">困难</a-select-option>
                <a-select-option :value="4">地狱</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>

        <a-form-item label="特殊说明">
          <a-textarea v-model:value="reassignForm.specialInstructions" :rows="3" placeholder="为新执行人提供特殊说明和注意事项" />
        </a-form-item>

        <a-form-item label="重新分配原因" required>
          <a-textarea v-model:value="reassignForm.reason" :rows="2" placeholder="请说明重新分配的原因" />
        </a-form-item>
      </a-form>
    </a-modal>

    <!-- 申诉处理模态框 -->
    <a-modal v-model:open="showAppealModal" title="申诉处理" width="600px" @ok="submitAppeal" :confirmLoading="saving">
      <a-form layout="vertical" v-if="selectedCase">
        <a-form-item label="申诉人">
          <a-input :value="selectedCase.name" disabled />
        </a-form-item>

        <a-form-item label="失败任务">
          <a-input :value="selectedCase.taskName" disabled />
        </a-form-item>

        <a-form-item label="当前判定">
          <a-input :value="getReasonText(selectedCase.failureReason)" disabled />
        </a-form-item>

        <a-form-item label="申诉理由" required>
          <a-select v-model:value="appealForm.appealReason" placeholder="选择申诉理由">
            <a-select-option value="misjudgment">判定错误</a-select-option>
            <a-select-option value="force_majeure">不可抗力</a-select-option>
            <a-select-option value="insufficient_time">时间不足</a-select-option>
            <a-select-option value="unclear_requirements">要求不明确</a-select-option>
            <a-select-option value="other">其他原因</a-select-option>
          </a-select>
        </a-form-item>

        <a-form-item label="请求处理方式" required>
          <a-select v-model:value="appealForm.requestedAction" placeholder="选择期望的处理方式">
            <a-select-option value="retry">重新尝试</a-select-option>
            <a-select-option value="reduce_penalty">减少惩罚</a-select-option>
            <a-select-option value="cancel_failure">撤销失败记录</a-select-option>
            <a-select-option value="extend_deadline">延长期限</a-select-option>
          </a-select>
        </a-form-item>

        <a-form-item label="支持证据">
          <a-textarea v-model:value="appealForm.evidence" :rows="3" placeholder="请提供支持申诉的证据和材料" />
        </a-form-item>

        <a-form-item label="详细说明" required>
          <a-textarea v-model:value="appealForm.explanation" :rows="4" placeholder="请详细说明申诉的具体情况和理由" />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { PlusOutlined, ExclamationCircleOutlined, ReloadOutlined, CheckCircleOutlined, BarChartOutlined, DownOutlined, UserSwitchOutlined, FileTextOutlined, MoreOutlined, TeamOutlined, CalendarOutlined } from '@ant-design/icons-vue'
import { message } from 'ant-design-vue'
import dayjs from 'dayjs'

// 响应式数据
const showHandlingModal = ref(false)
const showDetailModal = ref(false)
const showReassignModal = ref(false)
const showAppealModal = ref(false)
const saving = ref(false)
const selectedCase = ref(null)

// 表单数据
const handlingForm = ref({
  handlingPlan: '',
  actionTaken: '',
  penaltyPoints: 0,
  deadline: null,
  reassignTo: '',
  trainingRequired: false,
  notes: ''
})

const reassignForm = ref({
  newAssignee: '',
  newDeadline: null,
  adjustedDifficulty: 2,
  specialInstructions: '',
  reason: ''
})

const appealForm = ref({
  appealReason: '',
  requestedAction: '',
  evidence: '',
  explanation: ''
})

// 新建处理方案模态框
const showCreateModal = ref(false)
const createMode = ref('select') // 'select' or 'quick' or 'template'
const caseSearchKeyword = ref('')
const caseStatusFilter = ref('')
const selectedCases = ref([])
const filteredCases = ref([])
const selectedTemplate = ref(null)

// 快速处理方案模态框
const showQuickPlanModal = ref(false)
const quickPlanForm = ref({
  template: 'timeout',
  priority: 'medium',
  title: '',
  plan: '',
  actions: '',
  penaltyPoints: 0,
  deadline: null,
  retryCount: 0,
  options: [],
  applicableTypes: [],
  notes: ''
})
const quickPlanSaving = ref(false)
const previewPlan = ref(null)

// 方案模板管理
const showTemplateModal = ref(false)
const templateForm = ref({
  name: '',
  type: 'timeout',
  priority: 'medium',
  description: '',
  planTemplate: '',
  actionsTemplate: '',
  applicableTypes: []
})
const templateSaving = ref(false)
const planTemplates = ref([
  {
    id: 1,
    name: '超时处理模板',
    type: 'timeout',
    priority: 'urgent',
    description: '针对参与者因超时未完成任务的快速处理模板。',
    planTemplate: '1. 分析超时原因，如网络问题、设备故障、个人原因等。\n2. 确认超时时间点，记录具体时间。\n3. 与参与者沟通，了解其超时原因。\n4. 根据超时原因，制定相应的补救措施。\n5. 重新评估任务难度，必要时调整。',
    actionsTemplate: '1. 提供技术支持或指导。\n2. 调整任务截止时间。\n3. 重新分配任务给其他志愿者。\n4. 加强监督，确保任务按时完成。',
    applicableTypes: ['timeout'],
    usageCount: 0
  },
  {
    id: 2,
    name: '未完成处理模板',
    type: 'incomplete',
    priority: 'high',
    description: '针对参与者因各种原因未完成任务的快速处理模板。',
    planTemplate: '1. 分析未完成原因，如任务难度过高、资源不足、个人意愿等。\n2. 与参与者沟通，了解其未完成原因。\n3. 根据未完成原因，制定相应的补救措施。\n4. 重新评估任务难度，必要时调整。',
    actionsTemplate: '1. 提供额外资源或支持。\n2. 调整任务截止时间。\n3. 重新分配任务给其他志愿者。\n4. 加强监督，确保任务按时完成。',
    applicableTypes: ['incomplete'],
    usageCount: 0
  },
  {
    id: 3,
    name: '违规处理模板',
    type: 'violation',
    priority: 'urgent',
    description: '针对参与者在任务执行过程中出现违规行为的快速处理模板。',
    planTemplate: '1. 记录违规行为，包括时间、地点、具体行为。\n2. 与参与者沟通，了解其违规原因。\n3. 根据违规原因，制定相应的补救措施。\n4. 重新评估任务难度，必要时调整。',
    actionsTemplate: '1. 取消其参与资格。\n2. 记录违规行为。\n3. 重新分配任务给其他志愿者。\n4. 加强监督，确保任务按时完成。',
    applicableTypes: ['violation'],
    usageCount: 0
  },
  {
    id: 4,
    name: '放弃处理模板',
    type: 'abandon',
    priority: 'low',
    description: '针对参与者主动放弃任务的快速处理模板。',
    planTemplate: '1. 记录放弃原因，包括时间、地点、具体原因。\n2. 与参与者沟通，了解其放弃原因。\n3. 根据放弃原因，制定相应的补救措施。\n4. 重新评估任务难度，必要时调整。',
    actionsTemplate: '1. 重新评估参与者状况，考虑降低任务难度。\n2. 重新分配任务给其他志愿者。\n3. 加强监督，确保任务按时完成。',
    applicableTypes: ['abandon'],
    usageCount: 0
  }
])

// 方案预览
const showPreviewModal = ref(false)

// 失败案例数据
const failureData = ref([
  {
    id: 1,
    participantId: 'RS001',
    participantName: '张三',
    name: '张三',
    avatar: 'https://randomuser.me/api/portraits/men/1.jpg',
    taskName: '孤儿院志愿服务',
    difficulty: 2,
    taskDifficulty: 2,
    failureReason: 'timeout',
    failureTime: '2024-01-25',
    failureDate: '2024-01-25',
    penaltyAmount: 100,
    penaltyPoints: 100,
    penaltyApplied: true,
    handlingStatus: 'pending',
    status: 'pending',
    handlerName: null,
    level: 5,
    phoneNumber: '138****5678',
    email: 'zhangsan@example.com',
    totalMerit: 850,
    previousAttempts: 1,
    taskDuration: 7,
    assignedBy: '李导师',
    deadline: '2024-02-01',
    appealStatus: null,
    failureDescription: '参与者未能在规定时间内完成孤儿院志愿服务，缺少50%的服务时长记录。',
    handlingPlan: null,
    actionTaken: null,
    handlingDate: null,
    appealReason: null,
    notes: null
  },
  {
    id: 2,
    participantId: 'RS003',
    participantName: '王五',
    name: '王五',
    avatar: 'https://randomuser.me/api/portraits/women/1.jpg',
    taskName: '环保清洁行动',
    difficulty: 1,
    taskDifficulty: 1,
    failureReason: 'incomplete',
    failureTime: '2024-01-24',
    failureDate: '2024-01-24',
    penaltyAmount: 50,
    penaltyPoints: 50,
    penaltyApplied: false,
    handlingStatus: 'processing',
    status: 'processing',
    handlerName: '李处理员',
    level: 3,
    phoneNumber: '139****2345',
    email: 'wangwu@example.com',
    totalMerit: 420,
    previousAttempts: 0,
    taskDuration: 3,
    assignedBy: '王导师',
    deadline: '2024-01-30',
    appealStatus: null,
    failureDescription: '参与者完成了部分环保清洁行动，但未达到要求的清洁面积标准。',
    handlingPlan: '制定补充清洁计划，安排志愿者协助完成剩余工作。',
    actionTaken: '已联系志愿者团队，安排补充清洁行动。',
    handlingDate: '2024-01-25',
    appealReason: null,
    notes: '参与者态度良好，愿意配合完成补充工作。'
  },
  {
    id: 3,
    participantId: 'RS005',
    participantName: '赵六',
    name: '赵六',
    avatar: 'https://randomuser.me/api/portraits/men/3.jpg',
    taskName: '反思忏悔',
    difficulty: 3,
    taskDifficulty: 3,
    failureReason: 'violation',
    failureTime: '2024-01-23',
    failureDate: '2024-01-23',
    penaltyAmount: 200,
    penaltyPoints: 200,
    penaltyApplied: true,
    handlingStatus: 'completed',
    status: 'completed',
    handlerName: '王主管',
    level: 7,
    phoneNumber: '137****8901',
    email: 'zhaoliu@example.com',
    totalMerit: 1200,
    previousAttempts: 2,
    taskDuration: 14,
    assignedBy: '陈导师',
    deadline: '2024-02-05',
    appealStatus: 'processing',
    failureDescription: '参与者在反思忏悔过程中出现违规行为，未能按照要求完成心理疏导。',
    handlingPlan: '重新安排心理专家进行一对一辅导，延长反思期限。',
    actionTaken: '已安排专业心理咨询师介入，制定个性化康复计划。',
    handlingDate: '2024-01-24',
    appealReason: '认为判定过于严厉，请求减少惩罚措施。',
    notes: '参与者情绪波动较大，需要额外关注心理健康。'
  },
  {
    id: 4,
    participantId: 'RS007',
    participantName: '李四',
    name: '李四',
    avatar: 'https://randomuser.me/api/portraits/men/4.jpg',
    taskName: '社区服务',
    difficulty: 2,
    taskDifficulty: 2,
    failureReason: 'abandon',
    failureTime: '2024-01-22',
    failureDate: '2024-01-22',
    penaltyAmount: 150,
    penaltyPoints: 150,
    penaltyApplied: true,
    handlingStatus: 'appealing',
    status: 'appealing',
    handlerName: '张主管',
    level: 4,
    phoneNumber: '136****7890',
    email: 'lisi@example.com',
    totalMerit: 600,
    previousAttempts: 1,
    taskDuration: 10,
    assignedBy: '周导师',
    deadline: '2024-02-10',
    appealStatus: 'approved',
    failureDescription: '参与者主动放弃社区服务任务，未提供合理理由。',
    handlingPlan: '重新评估参与者状况，考虑降低任务难度。',
    actionTaken: '已与参与者深入沟通，了解放弃原因，准备重新安排任务。',
    handlingDate: '2024-01-23',
    appealReason: '因家庭突发事件无法继续参与，请求重新安排。',
    notes: '参与者家庭确实遇到困难，可考虑延期或调整任务。'
  }
])

// 初始化筛选数据
filteredCases.value = failureData.value

const columns = [
  { title: '参与者', key: 'participant', width: 200 },
  { title: '失败任务', key: 'task', width: 200 },
  { title: '失败原因', key: 'reason', width: 120 },
  { title: '惩罚措施', key: 'penalty', width: 120 },
  { title: '处理状态', key: 'status', width: 120 },
  { title: '失败时间', dataIndex: 'failureTime', width: 120 },
  { title: '处理人', dataIndex: 'handlerName', width: 120 },
  { title: '操作', key: 'actions', width: 120 }
]

const selectionColumns = [
  { title: '参与者', key: 'participant', width: 200 },
  { title: '失败任务', key: 'task', width: 200 },
  { title: '失败原因', key: 'reason', width: 120 },
  { title: '处理状态', key: 'status', width: 120 },
  { title: '操作', key: 'actions', width: 120 }
]

const pagination = ref({ pageSize: 10 })

const getDifficultyColor = (difficulty) => {
  const colors = { 1: 'green', 2: 'blue', 3: 'orange', 4: 'red' }
  return colors[difficulty] || 'default'
}

const getDifficultyText = (difficulty) => {
  const texts = { 1: '简单', 2: '普通', 3: '困难', 4: '地狱' }
  return texts[difficulty] || '未知'
}

const getReasonColor = (reason) => {
  const colors = { timeout: 'red', incomplete: 'orange', violation: 'error', abandon: 'default' }
  return colors[reason] || 'default'
}

const getReasonText = (reason) => {
  const texts = { timeout: '超时', incomplete: '未完成', violation: '违规', abandon: '放弃' }
  return texts[reason] || '未知'
}

const getStatusColor = (status) => {
  const colors = { pending: 'orange', processing: 'processing', completed: 'success', appealing: 'purple' }
  return colors[status] || 'default'
}

const getStatusText = (status) => {
  const texts = { pending: '待处理', processing: '处理中', completed: '已完成', appealing: '申诉中' }
  return texts[status] || '未知'
}

// 辅助函数
const getLevelColor = (level) => {
  if (level <= 3) return 'red'
  if (level <= 6) return 'orange'
  if (level <= 9) return 'blue'
  return 'purple'
}

const getAppealStatusColor = (status) => {
  const colors = {
    pending: 'orange',
    processing: 'blue',
    approved: 'green',
    rejected: 'red'
  }
  return colors[status] || 'default'
}

const getAppealStatusText = (status) => {
  const texts = {
    pending: '待审核',
    processing: '审核中',
    approved: '已批准',
    rejected: '已拒绝'
  }
  return texts[status] || '未知'
}

const getPriorityColor = (priority) => {
  const colors = { urgent: 'red', high: 'orange', medium: 'blue', low: 'green' }
  return colors[priority] || 'default'
}

const getPriorityText = (priority) => {
  const texts = { urgent: '紧急', high: '高', medium: '中等', low: '低' }
  return texts[priority] || '未知'
}

const getOptionText = (option) => {
  const texts = { training: '需要额外培训', reassign: '需要重新分配', supervision: '需要加强监督', counseling: '需要心理辅导' }
  return texts[option] || option
}

// 重置表单
const resetHandlingForm = () => {
  handlingForm.value = {
    handlingPlan: '',
    actionTaken: '',
    penaltyPoints: 0,
    deadline: null,
    reassignTo: '',
    trainingRequired: false,
    notes: ''
  }
}

const resetReassignForm = () => {
  reassignForm.value = {
    newAssignee: '',
    newDeadline: null,
    adjustedDifficulty: 2,
    specialInstructions: '',
    reason: ''
  }
}

const resetAppealForm = () => {
  appealForm.value = {
    appealReason: '',
    requestedAction: '',
    evidence: '',
    explanation: ''
  }
}

// 处理操作
const handleCreate = () => {
  // 打开新建处理方案模态框
  showCreateModal.value = true
  createMode.value = 'select'
  caseSearchKeyword.value = ''
  caseStatusFilter.value = ''
  selectedCases.value = []
  filteredCases.value = failureData.value
}

const handleMenuClick = ({ key }, record) => {
  selectedCase.value = record
  switch (key) {
    case 'view':
      showDetailModal.value = true
      break
    case 'reassign':
      resetReassignForm()
      showReassignModal.value = true
      break
    case 'modify':
      resetHandlingForm()
      handlingForm.value.penaltyPoints = record.penaltyPoints
      showHandlingModal.value = true
      break
    case 'appeal':
      resetAppealForm()
      showAppealModal.value = true
      break
  }
}

// 新建处理方案相关函数
const handleCreateModeChange = (key) => {
  createMode.value = key
  if (key === 'select') {
    caseSearchKeyword.value = ''
    caseStatusFilter.value = ''
    selectedCases.value = []
  }
}

const searchCases = () => {
  // 模拟搜索逻辑
  const keyword = caseSearchKeyword.value.toLowerCase()
  const status = caseStatusFilter.value
  filteredCases.value = failureData.value.filter((item) => {
    const matchesKeyword = item.participantName.toLowerCase().includes(keyword) || item.taskName.toLowerCase().includes(keyword)
    const matchesStatus = status === '' || item.handlingStatus === status
    return matchesKeyword && matchesStatus
  })
}

const filterCases = (value) => {
  searchCases()
}

const onCaseSelectionChange = (selectedRowKeys) => {
  selectedCases.value = selectedRowKeys
}

const batchCreatePlans = async () => {
  if (selectedCases.value.length === 0) {
    message.warning('请至少选择一个失败案例')
    return
  }

  saving.value = true
  try {
    await new Promise((resolve) => setTimeout(resolve, 1000))

    selectedCases.value.forEach((caseId) => {
      const caseItem = failureData.value.find((item) => item.id === caseId)
      if (caseItem) {
        const template = planTemplates.value.find((t) => t.type === caseItem.failureReason)
        if (template) {
          // 更新现有失败案例的处理状态
          const index = failureData.value.findIndex((item) => item.id === caseId)
          if (index !== -1) {
            failureData.value[index] = {
              ...failureData.value[index],
              handlingStatus: 'processing',
              status: 'processing',
              handlingPlan: template.planTemplate,
              actionTaken: template.actionsTemplate,
              handlerName: '当前用户',
              handlingDate: dayjs().format('YYYY-MM-DD'),
              notes: `批量创建，基于模板: ${template.name}`
            }
          }
        } else {
          message.warning(`未找到适用于案例 ${caseItem.participantName} - ${caseItem.taskName} 的模板`)
        }
      }
    })

    message.success(`成功批量创建 ${selectedCases.value.length} 个处理方案`)
    showCreateModal.value = false
    createMode.value = 'select'
    selectedCases.value = []
    filteredCases.value = failureData.value
  } catch (error) {
    message.error('批量创建失败，请重试')
  } finally {
    saving.value = false
  }
}

const createSinglePlan = (record) => {
  selectedCase.value = record
  resetHandlingForm()
  showHandlingModal.value = true
}

// 快速处理方案相关函数
const previewQuickPlan = () => {
  previewPlan.value = { ...quickPlanForm.value }
  showPreviewModal.value = true
}

const resetQuickPlanForm = () => {
  quickPlanForm.value = {
    template: 'timeout',
    priority: 'medium',
    title: '',
    plan: '',
    actions: '',
    penaltyPoints: 0,
    deadline: null,
    retryCount: 0,
    options: [],
    applicableTypes: [],
    notes: ''
  }
}

const saveQuickPlan = async () => {
  if (!quickPlanForm.value.title || !quickPlanForm.value.plan || !quickPlanForm.value.actions) {
    message.error('请填写所有必填信息')
    return
  }

  quickPlanSaving.value = true
  try {
    await new Promise((resolve) => setTimeout(resolve, 1000))

    // 模拟保存到数据库
    const newPlan = {
      ...quickPlanForm.value,
      id: failureData.value.length + 1, // 模拟ID
      participantId: 'RS00001', // 模拟参与者ID
      participantName: '当前用户', // 模拟参与者名称
      name: '当前用户', // 模拟名称
      avatar: 'https://randomuser.me/api/portraits/men/1.jpg', // 模拟头像
      taskName: '新任务', // 模拟任务名称
      difficulty: 2, // 模拟难度
      taskDifficulty: 2, // 模拟任务难度
      failureReason: 'custom', // 模拟失败原因
      failureTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
      failureDate: dayjs().format('YYYY-MM-DD'),
      penaltyAmount: quickPlanForm.value.penaltyPoints,
      penaltyPoints: quickPlanForm.value.penaltyPoints,
      penaltyApplied: false, // 模拟未执行
      handlingStatus: 'pending', // 模拟待处理
      status: 'pending', // 模拟待处理
      handlerName: null,
      level: 5, // 模拟等级
      phoneNumber: '13800000000', // 模拟电话
      email: 'user@example.com', // 模拟邮箱
      totalMerit: 1000, // 模拟功德总值
      previousAttempts: 0,
      taskDuration: 5, // 模拟任务时长
      assignedBy: '系统', // 模拟分配人
      deadline: quickPlanForm.value.deadline ? dayjs(quickPlanForm.value.deadline).format('YYYY-MM-DD') : null,
      appealStatus: null,
      failureDescription: '根据快速处理方案创建的失败记录。',
      handlingPlan: quickPlanForm.value.plan,
      actionTaken: quickPlanForm.value.actions,
      handlingDate: null,
      appealReason: null,
      notes: quickPlanForm.value.notes
    }
    failureData.value.push(newPlan)

    message.success('快速处理方案保存成功')
    showCreateModal.value = false
    createMode.value = 'select'
    resetQuickPlanForm()
  } catch (error) {
    message.error('保存快速方案失败，请重试')
  } finally {
    quickPlanSaving.value = false
  }
}

const handleTemplateChange = (value) => {
  const template = planTemplates.value.find((t) => t.type === value)
  if (template) {
    quickPlanForm.value = {
      ...quickPlanForm.value,
      template: value,
      plan: template.planTemplate,
      actions: template.actionsTemplate,
      penaltyPoints: template.penaltyPoints,
      retryCount: template.retryCount,
      options: template.options,
      applicableTypes: template.applicableTypes
    }
  }
}

// 方案模板管理相关函数
const handleTemplateAction = ({ key }, template) => {
  if (key === 'use') {
    quickPlanForm.value = {
      ...quickPlanForm.value,
      template: template.type,
      plan: template.planTemplate,
      actions: template.actionsTemplate,
      penaltyPoints: template.penaltyPoints,
      retryCount: template.retryCount,
      options: template.options,
      applicableTypes: template.applicableTypes
    }
    showCreateModal.value = false
    createMode.value = 'quick'
  } else if (key === 'edit') {
    selectedTemplate.value = template
    templateForm.value = {
      name: template.name,
      type: template.type,
      priority: template.priority,
      description: template.description,
      planTemplate: template.planTemplate,
      actionsTemplate: template.actionsTemplate,
      applicableTypes: template.applicableTypes
    }
    showTemplateModal.value = true
  } else if (key === 'copy') {
    const newTemplate = { ...template }
    newTemplate.id = planTemplates.value.length + 1
    newTemplate.name = `${newTemplate.name} (副本)`
    newTemplate.usageCount = 0 // 副本不计入使用次数
    planTemplates.value.push(newTemplate)
    message.success('模板已复制')
  } else if (key === 'delete') {
    planTemplates.value = planTemplates.value.filter((t) => t.id !== template.id)
    message.success('模板已删除')
  }
}

const saveTemplate = async () => {
  if (!templateForm.value.name || !templateForm.value.description || !templateForm.value.planTemplate || !templateForm.value.actionsTemplate) {
    message.error('请填写所有必填信息')
    return
  }

  templateSaving.value = true
  try {
    await new Promise((resolve) => setTimeout(resolve, 1000))

    if (selectedTemplate.value) {
      // 编辑现有模板
      const index = planTemplates.value.findIndex((t) => t.id === selectedTemplate.value.id)
      if (index !== -1) {
        planTemplates.value[index] = {
          ...planTemplates.value[index],
          name: templateForm.value.name,
          type: templateForm.value.type,
          priority: templateForm.value.priority,
          description: templateForm.value.description,
          planTemplate: templateForm.value.planTemplate,
          actionsTemplate: templateForm.value.actionsTemplate,
          applicableTypes: templateForm.value.applicableTypes
        }
      }
    } else {
      // 新建模板
      const newTemplate = {
        id: planTemplates.value.length + 1,
        name: templateForm.value.name,
        type: templateForm.value.type,
        priority: templateForm.value.priority,
        description: templateForm.value.description,
        planTemplate: templateForm.value.planTemplate,
        actionsTemplate: templateForm.value.actionsTemplate,
        applicableTypes: templateForm.value.applicableTypes,
        usageCount: 0
      }
      planTemplates.value.push(newTemplate)
    }

    message.success('模板保存成功')
    showTemplateModal.value = false
    selectedTemplate.value = null
    // 重置表单
    templateForm.value = {
      name: '',
      type: 'timeout',
      priority: 'medium',
      description: '',
      planTemplate: '',
      actionsTemplate: '',
      applicableTypes: []
    }
  } catch (error) {
    message.error('保存模板失败，请重试')
  } finally {
    templateSaving.value = false
  }
}

// 保存处理方案
const saveHandling = async () => {
  if (!handlingForm.value.handlingPlan || !handlingForm.value.actionTaken) {
    message.error('请填写处理计划和具体措施')
    return
  }

  saving.value = true
  try {
    // 模拟 API 调用
    await new Promise((resolve) => setTimeout(resolve, 1000))

    if (selectedCase.value) {
      // 更新现有案例
      const index = failureData.value.findIndex((item) => item.id === selectedCase.value.id)
      if (index !== -1) {
        failureData.value[index] = {
          ...failureData.value[index],
          handlingPlan: handlingForm.value.handlingPlan,
          actionTaken: handlingForm.value.actionTaken,
          penaltyPoints: handlingForm.value.penaltyPoints,
          deadline: handlingForm.value.deadline ? dayjs(handlingForm.value.deadline).format('YYYY-MM-DD') : null,
          handlerName: '当前用户',
          handlingDate: dayjs().format('YYYY-MM-DD'),
          status: 'processing',
          handlingStatus: 'processing',
          notes: handlingForm.value.notes
        }
      }
    }

    message.success('处理方案保存成功')
    showHandlingModal.value = false
    resetHandlingForm()
  } catch (error) {
    message.error('保存失败，请重试')
  } finally {
    saving.value = false
  }
}

// 重新分配
const submitReassign = async () => {
  if (!reassignForm.value.newAssignee || !reassignForm.value.newDeadline || !reassignForm.value.reason) {
    message.error('请填写所有必填信息')
    return
  }

  saving.value = true
  try {
    await new Promise((resolve) => setTimeout(resolve, 1000))

    const index = failureData.value.findIndex((item) => item.id === selectedCase.value.id)
    if (index !== -1) {
      failureData.value[index] = {
        ...failureData.value[index],
        status: 'processing',
        handlingStatus: 'processing',
        deadline: dayjs(reassignForm.value.newDeadline).format('YYYY-MM-DD'),
        difficulty: reassignForm.value.adjustedDifficulty,
        taskDifficulty: reassignForm.value.adjustedDifficulty,
        handlerName: '当前用户',
        handlingDate: dayjs().format('YYYY-MM-DD'),
        notes: reassignForm.value.reason
      }
    }

    message.success('重新分配成功')
    showReassignModal.value = false
    resetReassignForm()
  } catch (error) {
    message.error('重新分配失败，请重试')
  } finally {
    saving.value = false
  }
}

// 处理申诉
const submitAppeal = async () => {
  if (!appealForm.value.appealReason || !appealForm.value.requestedAction || !appealForm.value.explanation) {
    message.error('请填写所有必填信息')
    return
  }

  saving.value = true
  try {
    await new Promise((resolve) => setTimeout(resolve, 1000))

    const index = failureData.value.findIndex((item) => item.id === selectedCase.value.id)
    if (index !== -1) {
      failureData.value[index] = {
        ...failureData.value[index],
        status: 'appealing',
        handlingStatus: 'appealing',
        appealStatus: 'processing',
        appealReason: appealForm.value.explanation,
        handlerName: '当前用户',
        handlingDate: dayjs().format('YYYY-MM-DD')
      }
    }

    message.success('申诉提交成功')
    showAppealModal.value = false
    resetAppealForm()
  } catch (error) {
    message.error('申诉提交失败，请重试')
  } finally {
    saving.value = false
  }
}
</script>

<style lang="scss" scoped>
.failure-handling-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #1a1a2e 0%, #16213e 50%, #0f3460 100%);
  padding: 24px;

  .breadcrumb {
    margin-bottom: 24px;
    :deep(.ant-breadcrumb-link) {
      color: rgba(255, 255, 255, 0.65);
      &:hover {
        color: #ffd700;
      }
    }
    :deep(.ant-breadcrumb-separator) {
      color: rgba(255, 255, 255, 0.45);
    }
  }

  .page-header {
    margin-bottom: 32px;

    .page-title {
      color: #ffd700;
      font-size: 28px;
      font-weight: 600;
      margin: 0 0 8px 0;
    }

    .page-subtitle {
      color: rgba(255, 255, 255, 0.65);
      margin-bottom: 16px;
    }

    :deep(.ant-btn-primary) {
      background: linear-gradient(135deg, #ffd700 0%, #ffed4e 100%);
      border-color: #ffd700;
      color: #1a1a2e;
      &:hover {
        background: linear-gradient(135deg, #ffed4e 0%, #ffd700 100%);
        transform: translateY(-2px);
      }
    }
  }

  .stats-cards {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
    gap: 24px;
    margin-bottom: 32px;

    .stat-card {
      background: rgba(255, 255, 255, 0.08);
      backdrop-filter: blur(10px);
      border: 1px solid rgba(255, 255, 255, 0.1);
      border-radius: 12px;

      :deep(.ant-card-body) {
        padding: 24px;
      }

      .stat-content {
        display: flex;
        align-items: center;
        gap: 16px;

        .stat-icon {
          font-size: 24px;
          color: #ffd700;
        }

        .stat-info {
          .stat-value {
            font-size: 24px;
            font-weight: 600;
            color: #ffd700;
          }
          .stat-label {
            color: rgba(255, 255, 255, 0.65);
          }
        }
      }
    }
  }

  .table-card {
    background: rgba(255, 255, 255, 0.08);
    backdrop-filter: blur(10px);
    border: 1px solid rgba(255, 255, 255, 0.1);
    border-radius: 12px;

    :deep(.ant-table) {
      background: transparent;
      .ant-table-thead > tr > th {
        background: rgba(255, 255, 255, 0.05);
        color: rgba(255, 255, 255, 0.85);
      }
      .ant-table-tbody > tr > td {
        border-bottom: 1px solid rgba(255, 255, 255, 0.05);
        color: rgba(255, 255, 255, 0.85);
      }
    }
  }

  .participant-info {
    display: flex;
    align-items: center;
    gap: 12px;

    .name {
      color: #ffd700;
      font-weight: 500;
    }
    .id {
      color: rgba(255, 255, 255, 0.45);
      font-size: 12px;
    }
  }

  .task-info {
    .task-name {
      color: #ffd700;
      font-weight: 500;
      margin-bottom: 4px;
    }
  }

  .penalty-info {
    .penalty-value {
      color: #ff4d4f;
      font-weight: 500;
    }
    .penalty-status {
      color: rgba(255, 255, 255, 0.45);
      font-size: 12px;
    }
  }

  // 模态框样式
  :deep(.ant-modal) {
    .ant-modal-content {
      background: rgba(255, 255, 255, 0.95);
      backdrop-filter: blur(10px);
      border-radius: 16px;
      border: 1px solid rgba(255, 255, 255, 0.2);
    }

    .ant-modal-header {
      background: transparent;
      border-bottom: 1px solid rgba(255, 255, 255, 0.1);

      .ant-modal-title {
        color: #1a1a2e;
        font-weight: 600;
        font-size: 18px;
      }
    }

    .ant-modal-body {
      background: transparent;
      color: #1a1a2e;
    }

    .ant-modal-footer {
      background: transparent;
      border-top: 1px solid rgba(255, 255, 255, 0.1);
    }
  }

  // 表单样式
  :deep(.ant-form) {
    .ant-form-item-label > label {
      color: #1a1a2e;
      font-weight: 500;
    }

    .ant-input,
    .ant-input-number,
    .ant-select-selector,
    .ant-picker,
    .ant-textarea,
    .ant-checkbox-wrapper {
      background: rgba(255, 255, 255, 0.8);
      border: 1px solid rgba(255, 215, 0, 0.3);
      border-radius: 8px;
      color: #1a1a2e;

      &:hover {
        border-color: #ffd700;
      }

      &:focus,
      &.ant-input-focused,
      &.ant-picker-focused,
      &.ant-select-focused {
        border-color: #ffd700;
        box-shadow: 0 0 0 2px rgba(255, 215, 0, 0.2);
      }
    }

    .ant-select-arrow {
      color: #1a1a2e;
    }

    .ant-checkbox-wrapper {
      .ant-checkbox-inner {
        background: rgba(255, 255, 255, 0.8);
        border-color: rgba(255, 215, 0, 0.3);
      }

      .ant-checkbox-checked .ant-checkbox-inner {
        background: #ffd700;
        border-color: #ffd700;
      }
    }
  }

  // 详情模态框样式
  .failure-detail {
    .participant-card {
      background: rgba(255, 255, 255, 0.1);
      border: 1px solid rgba(255, 215, 0, 0.3);
      border-radius: 12px;

      .participant-info {
        text-align: center;
        padding: 16px;

        h3 {
          color: #1a1a2e;
          margin: 12px 0 8px 0;
          font-size: 18px;
          font-weight: 600;
        }

        .contact-info {
          margin: 16px 0;

          p {
            color: #666;
            margin: 4px 0;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 8px;
          }
        }

        .merit-info {
          margin: 16px 0;

          .merit-total {
            color: #1a1a2e;
            font-size: 14px;

            strong {
              color: #ffd700;
              font-size: 16px;
            }
          }
        }

        .attempts-info {
          margin-top: 16px;
        }
      }
    }

    .failure-info-card {
      background: rgba(255, 255, 255, 0.1);
      border: 1px solid rgba(255, 215, 0, 0.3);
      border-radius: 12px;

      h4 {
        color: #1a1a2e;
        font-size: 20px;
        font-weight: 600;
        margin-bottom: 8px;
      }

      .failure-date {
        color: #666;
        margin-bottom: 16px;
      }

      .failure-overview {
        margin: 16px 0;
      }

      .failure-description,
      .handling-info,
      .appeal-info {
        margin: 16px 0;

        p {
          color: #1a1a2e;
          line-height: 1.6;
          margin: 8px 0;
        }
      }
    }

    .additional-info {
      background: rgba(255, 255, 255, 0.1);
      border: 1px solid rgba(255, 215, 0, 0.3);
      border-radius: 12px;
    }
  }

  // 统计组件样式
  :deep(.ant-statistic) {
    .ant-statistic-title {
      color: #1a1a2e;
      font-weight: 500;
      margin-bottom: 8px;
    }

    .ant-statistic-content {
      color: #1a1a2e;
      font-weight: 600;
    }
  }

  // 描述列表样式
  :deep(.ant-descriptions) {
    .ant-descriptions-item-label {
      color: #1a1a2e;
      font-weight: 500;
    }

    .ant-descriptions-item-content {
      color: #1a1a2e;
    }
  }

  // 按钮样式
  :deep(.ant-btn) {
    border-radius: 8px;
    font-weight: 500;
    transition: all 0.3s ease;

    &.ant-btn-primary {
      background: linear-gradient(135deg, #ffd700 0%, #ffed4e 100%);
      border-color: #ffd700;
      color: #1a1a2e;

      &:hover {
        background: linear-gradient(135deg, #ffed4e 0%, #ffd700 100%);
        transform: translateY(-2px);
        box-shadow: 0 4px 12px rgba(255, 215, 0, 0.3);
      }
    }

    &.ant-btn-default {
      background: rgba(255, 255, 255, 0.1);
      border-color: rgba(255, 255, 255, 0.2);
      color: #1a1a2e;

      &:hover {
        background: rgba(255, 255, 255, 0.2);
        border-color: #ffd700;
        color: #1a1a2e;
      }
    }
  }

  // 分割线样式
  :deep(.ant-divider) {
    border-color: rgba(255, 215, 0, 0.3);

    &.ant-divider-with-text {
      color: #1a1a2e;
      font-weight: 500;
    }
  }

  // 标签样式
  :deep(.ant-tag) {
    border-radius: 6px;
    font-weight: 500;
    border: none;
    padding: 2px 8px;
  }

  // 警告框样式
  :deep(.ant-alert) {
    background: rgba(255, 193, 7, 0.1);
    border: 1px solid rgba(255, 193, 7, 0.3);
    border-radius: 8px;

    .ant-alert-message {
      color: #1a1a2e;
    }
  }

  // 下拉菜单样式
  :deep(.ant-dropdown) {
    .ant-dropdown-menu {
      background: rgba(255, 255, 255, 0.95);
      backdrop-filter: blur(10px);
      border-radius: 8px;
      border: 1px solid rgba(255, 215, 0, 0.3);

      .ant-dropdown-menu-item {
        color: #1a1a2e;

        &:hover {
          background: rgba(255, 215, 0, 0.1);
          color: #1a1a2e;
        }
      }
    }
  }

  // 分页样式
  :deep(.ant-pagination) {
    .ant-pagination-item {
      background: rgba(255, 255, 255, 0.1);
      border: 1px solid rgba(255, 255, 255, 0.2);

      a {
        color: rgba(255, 255, 255, 0.85);
      }

      &.ant-pagination-item-active {
        background: #ffd700;
        border-color: #ffd700;

        a {
          color: #1a1a2e;
        }
      }
    }

    .ant-pagination-prev,
    .ant-pagination-next {
      .ant-pagination-item-link {
        background: rgba(255, 255, 255, 0.1);
        border: 1px solid rgba(255, 255, 255, 0.2);
        color: rgba(255, 255, 255, 0.85);
      }
    }
  }

  // 新建处理方案模态框样式
  .create-plan-content {
    .case-selection {
      margin-bottom: 24px;

      .selection-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 16px;

        h4 {
          color: #ffd700;
          font-size: 18px;
          font-weight: 600;
          margin: 0;
        }
      }

      :deep(.ant-input-search) {
        .ant-input {
          background: rgba(255, 255, 255, 0.8);
          border: 1px solid rgba(255, 215, 0, 0.3);
          border-radius: 8px;
          color: #1a1a2e;

          &:hover {
            border-color: #ffd700;
          }

          &:focus {
            border-color: #ffd700;
            box-shadow: 0 0 0 2px rgba(255, 215, 0, 0.2);
          }
        }
      }

      :deep(.ant-select) {
        .ant-select-selector {
          background: rgba(255, 255, 255, 0.8);
          border: 1px solid rgba(255, 215, 0, 0.3);
          border-radius: 8px;
          color: #1a1a2e;

          &:hover {
            border-color: #ffd700;
          }
        }
      }

      :deep(.ant-table) {
        .ant-table-tbody > tr > td {
          color: rgba(255, 255, 255, 0.85);
        }
      }
    }

    .quick-plan {
      .ant-form-item {
        margin-bottom: 16px;
      }

      :deep(.ant-form-item-label) {
        color: #1a1a2e;
        font-weight: 500;
      }

      :deep(.ant-input),
      :deep(.ant-input-number),
      :deep(.ant-select-selector),
      :deep(.ant-picker),
      :deep(.ant-textarea),
      :deep(.ant-checkbox-wrapper) {
        background: rgba(255, 255, 255, 0.8);
        border: 1px solid rgba(255, 215, 0, 0.3);
        border-radius: 8px;
        color: #1a1a2e;

        &:hover {
          border-color: #ffd700;
        }

        &:focus,
        &.ant-input-focused,
        &.ant-picker-focused,
        &.ant-select-focused {
          border-color: #ffd700;
          box-shadow: 0 0 0 2px rgba(255, 215, 0, 0.2);
        }
      }

      :deep(.ant-select-arrow) {
        color: #1a1a2e;
      }

      :deep(.ant-checkbox-wrapper) {
        .ant-checkbox-inner {
          background: rgba(255, 255, 255, 0.8);
          border-color: rgba(255, 215, 0, 0.3);
        }

        .ant-checkbox-checked .ant-checkbox-inner {
          background: #ffd700;
          border-color: #ffd700;
        }
      }

      :deep(.ant-checkbox-group) {
        .ant-checkbox {
          color: #1a1a2e;
          font-weight: 500;
        }
      }
    }

    .template-management {
      .template-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 16px;

        h4 {
          color: #ffd700;
          font-size: 18px;
          font-weight: 600;
          margin: 0;
        }
      }

      .template-list {
        :deep(.ant-row) {
          gap: 16px;
        }

        .template-card {
          background: rgba(255, 255, 255, 0.08);
          border: 1px solid rgba(255, 255, 255, 0.1);
          border-radius: 12px;

          :deep(.ant-card-head) {
            background: transparent;
            border-bottom: 1px solid rgba(255, 255, 255, 0.1);

            .ant-card-head-title {
              color: #ffd700;
              font-weight: 600;
            }
          }

          :deep(.ant-card-body) {
            background: transparent;
          }

          .template-title {
            display: flex;
            align-items: center;
            gap: 8px;
            color: #ffd700;
            font-weight: 600;
          }

          .template-content {
            .template-description {
              color: rgba(255, 255, 255, 0.85);
              margin-bottom: 12px;
              line-height: 1.5;
            }

            .template-stats {
              display: flex;
              flex-direction: column;
              gap: 4px;

              .stat-item {
                color: rgba(255, 255, 255, 0.65);
                font-size: 12px;
                display: flex;
                align-items: center;
                gap: 4px;

                .anticon {
                  color: #ffd700;
                }
              }
            }
          }
        }
      }
    }
  }

  // 方案预览模态框样式
  .plan-preview {
    .ant-descriptions {
      .ant-descriptions-item-label {
        color: #1a1a2e;
        font-weight: 500;
      }

      .ant-descriptions-item-content {
        color: #1a1a2e;
      }
    }

    .plan-content,
    .actions-content,
    .notes-content {
      color: #1a1a2e;
      line-height: 1.6;
      margin: 16px 0;
      padding: 12px;
      background: rgba(255, 255, 255, 0.1);
      border: 1px solid rgba(255, 215, 0, 0.3);
      border-radius: 8px;
    }

    .options-content {
      .ant-tag {
        margin-right: 8px;
      }
    }
  }

  // 响应式设计
  @media (max-width: 768px) {
    .stats-cards {
      grid-template-columns: 1fr;
    }

    .failure-detail {
      .ant-row {
        flex-direction: column;

        .ant-col {
          width: 100%;
          margin-bottom: 16px;
        }
      }
    }
  }
}
</style>
